import { FC, useEffect, useRef, useState } from "react";
import {
  Button,
  Drawer,
  Form,
  Input,
  Select,
  DatePicker,
  Spin,
  Tabs,
  Row,
  Col,
} from "antd";
import repairService from "@/api/services/eam/repairService";
import type { EamEquipmentRepair } from "./entity";
import { toast } from "sonner";
import useDictionary from "@/hooks/system/useDictionary";
import EamEquipmentRepairAttachmentPage, {
  type EamEquipmentRepairAttachmentHandles,
} from "./attachment";
import EamEquipmentRepairPartPage, {
  type EamEquipmentRepairPartHandles,
} from "./part";
import EamEquipmentRepairReportPage, {
  type EamEquipmentRepairReportHandles,
} from "./report";
import dayjs from "dayjs";
import { UserAddOutlined } from "@ant-design/icons";
import SingleUserSelector from "@/pages/components/selector/SingleUserSelect";
import { UserInfo } from "#/entity";

const { TextArea } = Input;

interface EamEquipmentRepairPanelProps {
  visible: boolean;
  repair: EamEquipmentRepair;
  isView?: boolean;
  onClose: () => void;
}

const EamEquipmentRepairPanel: FC<EamEquipmentRepairPanelProps> = ({
  repair,
  visible,
  isView,
  onClose,
}) => {
  const attachmentRef = useRef<EamEquipmentRepairAttachmentHandles>(null);
  const partRef = useRef<EamEquipmentRepairPartHandles>(null);
  const reportRef = useRef<EamEquipmentRepairReportHandles>(null);

  const [submitLoading, setSubmitLoading] = useState(false);
  const [userSelectVisiable, setUserSelectVisiable] = useState(false);

  const [form] = Form.useForm();

  const repairStatusOptions = useDictionary("equipment_repair_status");
  const urgencyOptions = useDictionary("urgency_type");
  const repairModeOptions = useDictionary("equipment_repair_type");
  const repairResultOptions = useDictionary("equipment_repair_result");

  useEffect(() => {
    if (repair) {
      // 加载报修单数据
      form.setFieldsValue(repair);
      form.setFieldValue("repairStatus", "in_maintenance");
    }
  }, [repair]);

  //提交表单数据
  const handleSubmit = async (values: EamEquipmentRepair) => {
    try {
      setSubmitLoading(true);

      //设备维修附件
      const deleteAttachmentIds = attachmentRef.current?.getDeleteIds();
      const addAttachments = attachmentRef.current?.getAddList();
      const updateAttachments = attachmentRef.current?.getUpdateList();

      //设备维修备件
      const deletePartIds = partRef.current?.getDeleteIds();
      const addParts = partRef.current?.getAddList();
      const updateParts = partRef.current?.getUpdateList();

      //设备维修报告
      const repairReport = reportRef.current?.getReport();
      console.log("维修报告", repairReport);
      if (!repairReport) {
        throw new Error("请填写维修报告");
      }
      const data = {
        ...values,
        id: repair?.id,
        repairReport: repairReport,
        deleteAttachmentIds: deleteAttachmentIds,
        addAttachments: addAttachments,
        updateAttachments: updateAttachments,
        deletePartIds: deletePartIds,
        addParts: addParts,
        updateParts: updateParts,
      };
      await repairService.saveRecord(data);
      toast.success("更新设备维修单成功");
      form.resetFields();

      onClose();
    } catch (error) {
      toast.error(`保存失败: ${error.message}`);
    } finally {
      setSubmitLoading(false);
    }
  };

  const handleDrawerClose = () => {
    onClose();
    form.resetFields();
  };

  const showUserSelect = () => {
    setUserSelectVisiable(true);
  };
  const handleSelectUser = (user?: UserInfo) => {
    form.setFieldsValue({
      repairOwner: user?.id,
      repairOwnerName: user?.name,
    });
    setUserSelectVisiable(false);
  };

  // 故障信息
  const ErrorInfo = () => {
    return (
      <>
        <Row>
          <Col span={8}>
            <Form.Item
              name="urgency"
              label="紧急状态"
              rules={[
                {
                  required: true,
                  message: "请填写紧急状态",
                },
              ]}
            >
              <Select options={urgencyOptions} allowClear />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item name="requestUser" label="报修人" hidden>
              <Input disabled />
            </Form.Item>
            <Form.Item name="requestUserName" label="报修人">
              <Input disabled />
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item
              name="requestTime"
              label="报修时间"
              getValueFromEvent={(value) => {
                return value ? value.format("YYYY-MM-DD HH:mm:ss") : null;
              }}
              getValueProps={(value) => ({
                value: value ? dayjs(value, "YYYY-MM-DD HH:mm:ss") : undefined,
              })}
            >
              <DatePicker
                style={{ width: "100%" }}
                format="YYYY-MM-DD HH:mm:ss"
                onChange={(date) =>
                  date ? date.format("YYYY-MM-DD HH:mm:ss") : null
                }
                disabled
              />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={24}>
          <Col span={24}>
            <Form.Item
              name="symptoms"
              label="故障描述"
              labelCol={{ span: 2 }}
              wrapperCol={{ span: 22 }}
              rules={[
                {
                  required: true,
                  message: "请填写故障描述",
                },
              ]}
            >
              <TextArea rows={5} disabled />
            </Form.Item>
          </Col>
        </Row>
      </>
    );
  };

  return (
    <Spin spinning={submitLoading} tip="数据提交中..." size="large">
      <Drawer
        title="设备维修"
        width={1000}
        open={visible}
        onClose={handleDrawerClose}
        footer={
          <div className="flex justify-end gap-2">
            <Button onClick={handleDrawerClose}>取消</Button>
            <Button
              type="primary"
              loading={submitLoading}
              onClick={() => form.submit()}
            >
              确定
            </Button>
          </div>
        }
      >
        <Form
          form={form}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          onFinish={handleSubmit}
          disabled={isView}
        >
          <Row gutter={16}>
            <Col span={8}>
              <Form.Item name="code" label="维修单号">
                <Input disabled />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="equipmentId" label="设备" hidden>
                <Input />
              </Form.Item>
              <Form.Item name="equipmentCode" label="设备编码">
                <Input disabled />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="equipmentName" label="设备名称">
                <Input disabled />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item name="equipmentModel" label="设备型号">
                <Input disabled />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="equipmentTypeName" label="设备类型">
                <Input disabled />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="resourceOwner" label="设备负责人" hidden>
                <Input />
              </Form.Item>
              <Form.Item name="resourceOwnerName" label="设备负责人">
                <Input disabled />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item name="workshopId" label="车间" hidden>
                <Input disabled />
              </Form.Item>
              <Form.Item name="workshopName" label="车间">
                <Input disabled />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="repairMode"
                label="送修方式"
                rules={[
                  {
                    required: true,
                    message: "请填写送修方式",
                  },
                ]}
              >
                <Select options={repairModeOptions} allowClear />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="estimatedWorkOrderTime"
                label="预计完成时间"
                getValueFromEvent={(value) => {
                  return value ? value.format("YYYY-MM-DD") : null;
                }}
                getValueProps={(value) => ({
                  value: value ? dayjs(value, "YYYY-MM-DD") : undefined,
                })}
              >
                <DatePicker
                  style={{ width: "100%" }}
                  format="YYYY-MM-DD"
                  onChange={(date) => (date ? date.format("YYYY-MM-DD") : null)}
                  disabled
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item name="repairStatus" label="维修状态">
                <Select
                  options={repairStatusOptions}
                  allowClear
                  placeholder="请选择维修状态"
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="repairOwner" label="维修责任人" hidden>
                <Input />
              </Form.Item>
              <Form.Item name="repairOwnerName" label="维修责任人">
                <Input.Search
                  placeholder="请选择采购员"
                  allowClear
                  enterButton={<UserAddOutlined />}
                  onSearch={showUserSelect}
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item name="repairResult" label="维修结果">
                <Select
                  options={repairResultOptions}
                  allowClear
                  placeholder="请选择维修结果"
                />
              </Form.Item>
            </Col>
          </Row>

          <Tabs
            defaultActiveKey="1"
            items={[
              {
                key: "1",
                label: "故障信息",
                children: <ErrorInfo />,
              },
              {
                key: "2",
                label: "维修报告",
                children: (
                  <EamEquipmentRepairReportPage
                    ref={reportRef}
                    parentId={repair?.id}
                    isView={isView}
                  />
                ),
              },
              {
                key: "3",
                label: "设备维修备件",
                children: (
                  <EamEquipmentRepairPartPage
                    ref={partRef}
                    parentId={repair?.id}
                    isView={isView}
                  />
                ),
              },
              {
                key: "4",
                label: "设备维修附件",
                children: (
                  <EamEquipmentRepairAttachmentPage
                    ref={attachmentRef}
                    parentId={repair?.id}
                    isView={isView}
                  />
                ),
              },
            ]}
          />
        </Form>
      </Drawer>

      {/* 用户选择器 */}
      <SingleUserSelector
        open={userSelectVisiable}
        onCancel={() => setUserSelectVisiable(false)}
        onOk={(selectUser) => handleSelectUser(selectUser)}
      />
    </Spin>
  );
};

export default EamEquipmentRepairPanel;
